<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AES的JavaScript代码与Java代码同步加密测试</title>
  </head>
  <script src="https://cdn.bootcss.com/crypto-js/4.0.0/crypto-js.min.js"></script>
  <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
  <script>
    function aes_test() {
      // 要加密的数据
      const myData = document.getElementById("data").value;
      if (myData === "") {
        document.getElementById("booleanResult").innerHTML = "加密失败，请输入数据";
      } else {
        const data_clientAES = aes_client(myData);
        aes_server(myData);
        if (data_clientAES === document.getElementById("serverResult").innerHTML ) {
            document.getElementById("booleanResult").innerHTML = "同步加密成功";
        } else {
            document.getElementById("booleanResult").innerHTML = "同步加密失败";
        }
      }
    }
    function aes_client(mydata) {
      const key = CryptoJS.enc.Latin1.parse("abcdef0123456789");
      const iv = CryptoJS.enc.Latin1.parse("0123456789abcdef");
      const encrypted = CryptoJS.AES.encrypt(mydata, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding,
      });
      document.getElementById("clientResult").innerHTML = encrypted.toString();
      return encrypted.toString();
    }

    function aes_server(mydata) {
      const settings = {
        url: "http://localhost:8086/encrypt/aes_encrypt",
        method: "POST",
        timeout: 0,
        async: false,
        headers: {
          "Content-Type": "text/plain",
        },
        data: mydata,
      };

      $.ajax(settings).done(function (response) {
        document.getElementById("serverResult").innerHTML = response.data;
      });
    }
  </script>

  <body>
    <label for="data"></label><input id="data" type="text" placeholder="测试需要加密的data" />
    <button onclick="aes_test()">加密</button><br />
    服务端的加密结果
    <p id="serverResult"></p>
    <br />
    客户端的加密结果
    <p id="clientResult"></p>
    <br />
    服务端的加密结果是否等于客户端的加密结果：
    <p id="booleanResult" style="color: red"></p>
    <p>
      ==============================================================================
    </p>
  </body>
</html>
